import { validateDeviceId } from "@/utils/rules";
import { validatePublic, validateGatewayCode } from "@/utils/validate";

// 格式化表格中状态
function filterState(vm, h, state, demo) {
  let stateObject = {
    1: h(
      "Tag",
      {
        props: {
          color: "success"
        }
      },
      "正常"
    ),
    2: h(
      "Tag",
      {
        props: {
          color: "warning"
        }
      },
      "预警"
    ),
    3: h(
      "Tag",
      {
        props: {
          color: "error"
        }
      },
      "告警"
    ),
    4: h(
      "Tag",
      {
        props: {
          color: "default"
        }
      },
      "故障"
    )
  };
  if (!(state in stateObject)) {
    return h(
      "Tag",
      {
        props: {
          color: "grey"
        }
      },
      "未知"
    );
  }
  return stateObject[state];
}

// 按钮格式化
function filterHandle(vm, h, params, demo) {
  const row = JSON.parse(JSON.stringify(params.row));
  return h("div", [
    h(
      "Button",
      {
        props: {
          type: "primary",
          size: "small",
          disabled: demo
        },
        style: {
          marginRight: "5px"
        },
        on: {
          click: () => {
            const sessiongItem = Object.assign(vm.formHeader, {
              page: vm.pageInfo.page
            });
            sessionStorage.setItem("searchKey", JSON.stringify(sessiongItem));
            let id = row.id;
            vm.$router.push({
              path: "/device/info/" + id
            });
          }
        }
      },
      "查看详情"
    ),
    h(
      "Poptip",
      {
        props: {
          confirm: true,
          title: "您确定要删除这条数据吗?",
          transfer: true,
          cancelText: "取消"
        },
        on: {
          "on-ok": () => {
            vm.handleDelete(row);
          }
        }
      },
      [
        h(
          "Button",
          {
            props: {
              type: "error",
              size: "small",
              disabled: demo || row.company == "长沙平和堂五一广场店"
            }
          },
          "删除"
        )
      ]
    )
  ]);
}

export const generatedColumns = (vm, demo) => {
  return [
    {
      title: "是否在线",
      key: "online",
      align: "center",
      render: (h, params) => {
        let tag = params.row.online;
        if (!!tag) {
          return h(
            "Tag",
            {
              props: {
                color: "green"
              }
            },
            "在线"
          );
        } else {
          return h(
            "Tag",
            {
              props: {
                color: "red"
              }
            },
            "离线"
          );
        }
      }
    },
    {
      title: "启动/停止",
      align: "center",
      render: (h, params) => {
        let row = { ...params.row };
        const start = row.start,
          disabled = !!row.online && !!row.port;
        if (start) {
          return h(
            "Button",
            {
              props: {
                type: "error",
                size: "small",
                disabled: demo || row.company === "长沙平和堂五一广场店"
              },
              on: {
                click: () => {
                  vm._stopDevice(row);
                }
              }
            },
            "停止"
          );
        } else {
          return h(
            "Button",
            {
              props: {
                type: "primary",
                size: "small",
                disabled:
                  demo || !disabled || row.company === "长沙平和堂五一广场店"
              },
              on: {
                click: () => {
                  vm._startDevice(row);
                }
              }
            },
            "启动"
          );
        }
      }
    },
    {
      title: "设备ID",
      key: "deviceId",
      width: 180,
      align: "center"
    },
    {
      title: "端口",
      align: "center",
      render: (h, params) => {
        let vm = vm;
        let port = params.row.port;
        if (!!port) {
          return h("span", port);
        }
        return h("span", "-");
      }
    },
    {
      title: "设备名称",
      key: "name",
      align: "center"
    },
    {
      title: "设备位置",
      key: "location",
      align: "center"
    },
    {
      title: "所属企业",
      key: "company",
      align: "center"
    },
    {
      title: "创建时间",
      align: "center",
      render: (h, params) => {
        let row = { ...params.row };
        return h("span", vm.moment(row.createdAt).format("YYYY-MM-DD"));
      }
    },
    {
      title: "当前状态",
      align: "center",
      render: (h, params) => filterState(vm, h, params.row.state)
    },
    {
      title: "操作",
      align: "center",
      width: 200,
      render: (h, params) => filterHandle(vm, h, params, demo)
    }
  ];
};

export const generateRules = () => {
  return {
    companyId: [
      {
        required: true,
        trigger: "change",
        message: "请选择所属客户"
      }
    ],
    groupId: [
      {
        required: true,
        trigger: "change",
        message: "请选择所属区域"
      }
    ],
    name: [
      {
        required: true,
        validator: validatePublic(
          "设备名称",
          "设备名称只能输入中文、字母、数字、下划线、中划线"
        ),
        trigger: "blur"
      }
    ],
    alias: [
      {
        required: true,
        validator: validatePublic(
          "设备别名",
          "设备别名只能输入中文、字母、数字、下划线、中划线"
        ),
        trigger: "blur"
      }
    ],
    deviceId: [
      {
        required: true,
        validator: validateDeviceId("设备ID", "设备ID只能输入数字"),
        trigger: "blur"
      },
      {
        min: 12,
        message: "设备ID不得少于12个字符"
      }
    ],
    location: [
      {
        required: true,
        validator: validatePublic(
          "设备位置",
          "设备位置只能输入中文、字母、数字、下划线、中划线"
        ),
        trigger: "blur"
      }
    ],
    rate: [
      {
        required: true,
        validator: validateDeviceId("采集频率", "采集频率只能输入正整数"),
        trigger: "blur"
      }
    ],
    ct: [
      {
        required: true,
        validator: validateDeviceId("CT值", "CT值只能输入正整数"),
        trigger: "blur"
      }
    ],
    pt: [
      {
        required: true,
        validator: validateDeviceId("PT值", "PT值只能输入正整数"),
        trigger: "blur"
      }
    ],
    lct: [
      {
        required: true,
        validator: validateDeviceId("LCT值", "LCT值只能输入正整数"),
        trigger: "blur"
      }
    ],
    disconState: [
      {
        required: true,
        message: "是否启用断路功能"
      }
    ],
    enable: [
      {
        required: true,
        message: "是否启用"
      }
    ],
    deviceType: [
      {
        required: true,
        message: "请选择设备类型"
      }
    ],
    collectType: [
      {
        required: true,
        message: "请选择采集方式"
      }
    ],
    port: [
      {
        required: true,
        trigger: "blur",
        type: "number",
        message: "请输入设备端口"
        // validator: validatePort(
        //   "端口",
        //   "端口值只能输入正整数并且介于20001-30000之间"
        // )
      }
    ],
    gatewayType: [
      {
        required: true,
        message: "请选择网关类型"
      }
    ],
    gatewayCode: [
      {
        required: true,
        trigger: "blur",
        validator: validateGatewayCode(
          "网关地址码",
          "网关地址码只能输入1-255的数字"
        )
      }
    ],
    gatewayPort: [
      {
        type: "number",
        required: true,
        message: "请选择网关端口"
      }
    ],
    deviceLevel: [
      {
        required: true,
        message: "请选择设备级别"
      }
    ],
    deviceParent: [
      {
        required: true,
        message: "请选择上级设备"
      }
    ],
    calculateStatus: [
      {
        required: true,
        type: "boolean",
        message: "是否启用软件计算功能"
      }
    ],
    lineToZeroLine: [
      {
        required: true,
        type: "boolean",
        message: "是否接入零线"
      }
    ],
    showZeroLine: [
      {
        required: true,
        type: "boolean",
        message: "零线设备是否显示"
      }
    ],
    childDeviceName: [
      {
        required: true,
        message: "请输入零线设备名称"
      }
    ],
    stata_port: [
      {
        required: true,
        message: "请输入串口端口"
      }
    ],
    stata_addr: [
      {
        required: true,
        trigger: "blur",
        validator: validateGatewayCode(
          "串口地址码",
          "串口地址码只能输入1-255的数字"
        )
      }
    ]
  };
};

/**
 *
 * 用电安全探测终端-SEFM-117  8通道，组合式电气火灾探测器-WEFC-117”、“组合式电气火灾探测器-QJ-M4  4通道
 * 设备类型为2 是8通道
 */
export const deviceTypes = [
  {
    name: "用电安全监控终端-基础型-SEFM-106",
    id: 0
  },
  {
    name: "用电安全监控终端-漏电型-SEFM-106",
    id: 1
  },
  {
    name: "用电安全探测终端-SEFM-117",
    id: 2
  },
  {
    name: "电气火灾监控设备-WEFE-173",
    id: 3
  },
  {
    // 4通道
    name: "组合式电气火灾探测器-WEFC-117",
    id: 4
  },
  {
    // 4通道
    name: "组合式电气火灾探测器-QJ-M4",
    id: 5
  },
  {
    name: "温湿度变送器（非防爆）-JWSK-6",
    id: 6
  },
  {
    name: "温湿度变送器（防爆）-JWSK-6",
    id: 7
  },
  {
    name: "故障电弧探测器	AFD-XY32i",
    id: 8
  }
];

export const collectTypes = [
  {
    name: "网关",
    id: 1
  },
  {
    name: "DTU",
    id: 2
  }
];

export const deviceLevelList = [
  {
    id: 1,
    name: "变压器"
  },
  {
    id: 2,
    name: "二级表"
  },
  {
    id: 3,
    name: "三级表"
  },
  {
    id: 4,
    name: "四级表"
  }
];

export const columnsPipe = [
  {
    title: "通道序号",
    key: "channel",
    align: "center"
  },
  {
    title: "通道类型",
    key: "channelType",
    align: "center",
    $selectable: true
  },
  {
    title: "通道别名",
    key: "channelAlias",
    align: "center",
    $editable: true
  },
  {
    title: "告警值",
    key: "errorUp",
    align: "center",
    $number: true
  },
  {
    title: "操作",
    align: "center",
    key: "handle",
    $handle: ["edit"]
  }
];

export const fourTablePipe = [...new Array(4)].map((_, i) => {
  return {
    channel: ++i,
    channelAlias: null,
    channelType: null,
    errorUp: null
  };
});

export const eightTablePipe = [...new Array(8)].map((_, i) => {
  return {
    channel: ++i,
    channelAlias: null,
    channelType: null,
    errorUp: null
  };
});

export function isNullObject(arr) {
  let newArr = arr.filter(t => {
    return isNull(Object.values(t));
  });
  return newArr;
}
function isNull(arr) {
  let flag = true;
  for (let i = 0; i < arr.length; i++) {
    if ((!arr[i] || arr[i] == "null" || arr[i] == "undefined") && arr[i] != 0) {
      flag = false;
      break;
    } else {
      flag = true;
    }
  }
  return flag;
}
/**
 *
 * @param {*} value
 * @param {*} key
 * @param {*} array
 */
export function itemIsInArray(value, key, array) {
  return array.some((t, i) => {
    if (t[key] === value) return i;
    return false;
  });
}
